<template>
  <div class="app-container">
    <!-- 查询表单 - 布局优化和tooltip -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="故障ID" prop="reportId">
            <el-input
                v-model="queryParams.reportId"
                placeholder="请输入故障ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="repairResult">
            <template #label>
              <el-tooltip content="1-已修复,2-未修复,3-无法修复" placement="top">
                <span>处理结果</span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.repairResult" placeholder="请选择处理结果" clearable style="width: 100%;">
              <el-option
                  v-for="dict in fault_result"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker clearable
                            v-model="queryParams.startTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择开始时间"
                            style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="完成时间" prop="endTime">
            <el-date-picker clearable
                            v-model="queryParams.endTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择完成时间"
                            style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item prop="repairHours">
            <template #label>
              <el-tooltip content="单位为小时" placement="top">
                <span>处理耗时</span>
              </el-tooltip>
            </template>
            <el-input
                v-model="queryParams.repairHours"
                placeholder="请输入处理耗时"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="处理人" prop="repairBy">
            <el-input
                v-model="queryParams.repairBy"
                placeholder="请输入处理人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="status">
            <template #label>
              <el-tooltip content="0-待处理,1-处理中,2-已完成" placement="top">
                <span>处理状态</span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.status" placeholder="请选择处理状态" clearable style="width: 100%;">
              <el-option
                  v-for="dict in fault_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['fault:repair:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['fault:repair:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['fault:repair:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['fault:repair:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主表格 - 列宽优化和tooltip -->
    <el-table v-loading="loading" :data="repairList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="处理ID" align="center" prop="id" width="80" />
      <el-table-column label="故障ID" align="center" prop="reportId" width="90" />
      <el-table-column label="处理描述" align="center" prop="repairDesc" min-width="180" :show-overflow-tooltip="true" />
      <el-table-column label="处理方法" align="center" prop="repairMethod" min-width="180" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="repairResult" width="120">
        <template #header>
          <el-tooltip content="1-已修复,2-未修复,3-无法修复" placement="top">
            <span>处理结果</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="fault_result" :value="scope.row.repairResult"/>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="endTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="repairHours" width="100">
        <template #header>
          <el-tooltip content="单位为小时" placement="top">
            <span>处理耗时</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <span>{{ scope.row.repairHours }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="repairBy" width="100" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="status" width="100">
        <template #header>
          <el-tooltip content="0-待处理,1-处理中,2-已完成" placement="top">
            <span>处理状态</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="fault_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fault:repair:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fault:repair:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改故障处理对话框 - 尺寸、布局优化和tooltip -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="repairRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="故障ID" prop="reportId">
              <el-input v-model="form.reportId" placeholder="请输入故障ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="repairResult">
              <template #label>
                <el-tooltip content="1-已修复,2-未修复,3-无法修复" placement="top">
                  <span>处理结果</span>
                </el-tooltip>
              </template>
              <el-select v-model="form.repairResult" placeholder="请选择处理结果" style="width: 100%;">
                <el-option
                    v-for="dict in fault_result"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable
                              v-model="form.startTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择开始时间"
                              style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成时间" prop="endTime">
              <el-date-picker clearable
                              v-model="form.endTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择完成时间"
                              style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="repairHours">
              <template #label>
                <el-tooltip content="单位为小时" placement="top">
                  <span>处理耗时</span>
                </el-tooltip>
              </template>
              <el-input v-model="form.repairHours" placeholder="请输入处理耗时" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理人" prop="repairBy">
              <el-input v-model="form.repairBy" placeholder="请输入处理人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="status">
              <template #label>
                <el-tooltip content="0-待处理,1-处理中,2-已完成" placement="top">
                  <span>处理状态</span>
                </el-tooltip>
              </template>
              <el-select v-model="form.status" placeholder="请选择处理状态" style="width: 100%;">
                <el-option
                    v-for="dict in fault_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理描述" prop="repairDesc">
              <el-input v-model="form.repairDesc" type="textarea" :rows="3" placeholder="请输入处理描述内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="处理方法" prop="repairMethod">
          <el-input v-model="form.repairMethod" type="textarea" :rows="3" placeholder="请输入处理方法内容" />
        </el-form-item>

        <el-divider content-position="left">维修人员分配信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddFaultAssign">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteFaultAssign">删除</el-button>
          </el-col>
        </el-row>
        <!-- 子表格 - 列宽优化和max-height -->
        <el-table :data="faultAssignList" :row-class-name="rowFaultAssignIndex" @selection-change="handleFaultAssignSelectionChange" ref="faultAssign" max-height="200px">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          <el-table-column label="用户ID" prop="userId" width="120" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.userId" placeholder="请输入用户ID" />
            </template>
          </el-table-column>
          <el-table-column prop="assignType" width="120">
            <template #header>
              <el-tooltip content="1-负责人,2-实施人" placement="top">
                <span>分配类型</span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-select v-model="scope.row.assignType" placeholder="请选择类型">
                <el-option
                    v-for="dict in mission_personnel"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <!-- 假设还能添加更多与分配相关的信息，例如昵称、部门等，可增加列 -->
          <el-table-column label="备注" prop="remark" min-width="150" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Repair">
import { listRepair, getRepair, delRepair, addRepair, updateRepair } from "@/api/fault/repair"

const { proxy } = getCurrentInstance()
const { fault_result, fault_status, mission_personnel } = proxy.useDict('fault_result', 'fault_status', 'mission_personnel')

const repairList = ref([])
const faultAssignList = ref([]) // 子表数据
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedFaultAssign = ref([]) // 子表选中项
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    // 确保faultAssignList在form中初始化
    faultAssignList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reportId: null,
    repairDesc: null,
    repairMethod: null,
    repairResult: null,
    startTime: null,
    endTime: null,
    repairHours: null,
    repairBy: null,
    status: null,
  },
  rules: {
    reportId: [
      { required: true, message: "故障ID不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "处理状态不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询故障处理列表 */
function getList() {
  loading.value = true
  listRepair(queryParams.value).then(response => {
    repairList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    reportId: null,
    repairDesc: null,
    repairMethod: null,
    repairResult: null,
    startTime: null,
    endTime: null,
    repairHours: null,
    repairBy: null,
    status: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    faultAssignList: [] // 重置时清空子列表
  }
  faultAssignList.value = [] // 确保响应式变量也重置
  proxy.resetForm("repairRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加故障处理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRepair(_id).then(response => {
    form.value = response.data
    // 确保从后端返回的faultAssignList是数组
    faultAssignList.value = response.data.faultAssignList || []
    open.value = true
    title.value = "修改故障处理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["repairRef"].validate(valid => {
    if (valid) {
      form.value.faultAssignList = faultAssignList.value
      if (form.value.id != null) {
        updateRepair(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRepair(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除故障处理编号为"' + _ids + '"的数据项？').then(function() {
    return delRepair(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 维修人员分配序号 */
function rowFaultAssignIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 维修人员分配添加按钮操作 */
function handleAddFaultAssign() {
  let obj = {
    userId: "",
    assignType: "",
    remark: "", // 添加备注字段
  }
  faultAssignList.value.push(obj)
}

/** 维修人员分配删除按钮操作 */
function handleDeleteFaultAssign() {
  if (checkedFaultAssign.value.length === 0) {
    proxy.$modal.msgError("请先选择要删除的维修人员分配数据")
  } else {
    // 过滤掉选中的行，并重新为剩余行设置索引
    faultAssignList.value = faultAssignList.value.filter(item => !checkedFaultAssign.value.includes(item.index));
    // 清空选中项
    checkedFaultAssign.value = [];
    // 强制刷新表格选中状态，确保UI同步
    proxy.$nextTick(() => {
      proxy.$refs.faultAssign.clearSelection();
    });
  }
}

/** 复选框选中数据 */
function handleFaultAssignSelectionChange(selection) {
  checkedFaultAssign.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('fault/repair/export', {
    ...queryParams.value
  }, `repair_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
/* 可以在这里添加一些样式来微调布局，例如： */
.el-row {
  margin-bottom: 10px; /* 增加行之间的间距，保持视觉平衡 */
}
.el-form-item {
  margin-bottom: 0; /* 在el-row中已经有间距，减少form-item自带的冗余间距 */
}
</style>
